package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.disbursing

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.review.showMessage
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.review.startNextActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.subview.HotlineCameroonDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.tabrepay.TabRepayCameroonActivity
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonDisbursingBinding
import org.json.JSONObject

class DisbursingCameroonActivity : AppCompatActivity() {

    private lateinit var disbursingViewModel: DisbursingCameroonViewModel
    private lateinit var binding: ActivityCameroonDisbursingBinding
    private lateinit var adapter: DisbursingCameroonPageAdapter

    @SuppressLint("NotifyDataSetChanged", "ResourceType")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        disbursingViewModel = ViewModelProvider(this)[DisbursingCameroonViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonDisbursingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val back = binding.navbarLeft
        val hotline = binding.navbarRight
        val loading = binding.loading
        val list = binding.list
        val refresh = binding.refresh

        // 初始化下拉刷新
        refresh.apply {
            setColorSchemeColors(Color.parseColor("#5277D6"))

            setOnRefreshListener { disbursingViewModel.pageDetail() }
        }

        // 初始化adapter
        adapter = DisbursingCameroonPageAdapter(emptyList())
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 页面loading状态接口监听
        disbursingViewModel.loadingResult.observe(this@DisbursingCameroonActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                refresh.isRefreshing = false
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        disbursingViewModel.pageDetailResult.observe(this@DisbursingCameroonActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (pageDetailResult.error != null) {
                // TODO: 失败
                showMessage(pageDetailResult.error)
            }
            if (pageDetailResult.success != null) {
                // TODO: 成功
                binding.loanAmount.text = pageDetailResult.success.optString("amountFormat")
                binding.loanTerm.text = pageDetailResult.success.optString("daysFormat")
            }
        })

        // 卡列表接口监听
        disbursingViewModel.walletResult.observe(this@DisbursingCameroonActivity, Observer {
            val walletResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (walletResult.error != null) {
                // TODO: 失败
                showMessage(walletResult.error)
            }
            if (walletResult.success != null) {
                // TODO: 成功
                binding.walletName.text = walletResult.success.optString("walletType")
                binding.walletMobile.text = walletResult.success.optString("walletMobile")

                val logo = walletResult.success.optString("walletLogo")
                if (logo.startsWith("http")) {
                    Glide.with(this).load(logo).into(binding.walletLogo)
                }
            }
        })

        // 推荐产品列表接口监听
        disbursingViewModel.commendProductsResult.observe(this@DisbursingCameroonActivity, Observer {
            val commendProductsResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (commendProductsResult.error != null) {
                // TODO: 失败
                showMessage(commendProductsResult.error)
            }
            if (commendProductsResult.success != null) {
                // TODO: 成功
                adapter.dataList = commendProductsResult.success
                adapter.notifyDataSetChanged()
                if (commendProductsResult.success.isEmpty()) {
                    binding.recommendBg.visibility = View.GONE
                } else {
                    binding.recommendBg.visibility = View.VISIBLE
                }
            }
        })

        // 点击申请
        back.setOnClickListener {
            startNextActivity(TabRepayCameroonActivity::class.java)
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineCameroonDialog().showNow(supportFragmentManager, "hotline")
            hitPointCameroon("SHOW_HOTLINE")
        }

        // 查询页面详情
        disbursingViewModel.pageDetail()

        // 查询产品列表
        disbursingViewModel.commendProducts()
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)
    }
}


class DisbursingCameroonPageAdapter(
    var dataList: List<JSONObject>
) :
    RecyclerView.Adapter<DisbursingCameroonPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_cameroon_disbursing_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val icon: ImageView = view.findViewById(R.id.icon)
        private val name: TextView = view.findViewById(R.id.name)
        private val amount: TextView = view.findViewById(R.id.amount)
        private val star: TextView = view.findViewById(R.id.star)
        private val download: TextView = view.findViewById(R.id.download)
        private val installBg: LinearLayout = view.findViewById(R.id.installBg)

        fun bindData(item: JSONObject) {
            val product = item.optString("product")
            name.text = item.optString("appName")
            amount.text = item.optString("appLoanAmount")
            star.text = item.optString("star")
            download.text = item.optString("download")

            val logo = item.optString("appLogo")
            if (logo.isNotBlank()) {
                icon.visibility = View.VISIBLE
                Glide.with(icon).load(logo).into(icon)
            } else {
                icon.visibility = View.GONE
            }

            val link = item.optString("appLink")
            installBg.setOnClickListener {
                if (link.isNotBlank()) {
                    installBg.context.hitPointCameroon("DC_INSTALL_CLICK", product)

                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    }
                    if (intent.resolveActivity(ProjectApplication.instance.packageManager) != null) {
                        ProjectApplication.instance.startActivity(intent)
                    } else {
                        ProjectApplication.instance.startActivity(
                            Intent.createChooser(intent, "Please select a browser to open")
                        )
                    }
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}